/*Author: Rony Lahav (ID:043489889)*/

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * Activates the FT command by loading a file to transmit and running FTManager
 */
public class CmdFT implements ICmd{

	private String fileName;
	
	public CmdFT(String file) throws IOException{
		this.fileName=file;
	}
	
	//Sends a GET message to all peers
	public void executeCmd(){
		if (!final_project.isShutDown()){
			if (fileName.endsWith(final_project.outputFilePath))
				Logger.getInstance().closeFileAndStopWriting();
			try {
				loadFileForTransfer();
			} catch (IOException e) {}
			if (final_project.amIanSN){	//send to peers and SNs
				FTManager.getInstance().sendFTToPeers(fileName, final_project.getMyPeerID());
				FTManager.getInstance().sendFTToAllSNs(fileName, final_project.getMyKey());
			}
			else if (final_project.inFallBackMode)
				FTManager.getInstance().sendFTToPeers(fileName, final_project.getMyPeerID());
			else	//regular peer
				FTManager.getInstance().sendFTToSN(fileName);
		}
	}
	
	/**
	 * load a file to be ready to transfer
	 */
	public void loadFileForTransfer() throws IOException{
		if(!final_project.isShutDown()){
			String pictureFilePath = final_project.currentDir+"/files/"+fileName;
			if (final_project.loadedFiles.get(fileName)==null){	//file not already loaded
				//reading the picture file
				try {
					File picture = new File(pictureFilePath);
					FileInputStream in = new FileInputStream(picture);
					byte[] picBytes = new byte[(int) picture.length()];
					in.read(picBytes);
					final_project.loadedFiles.put(fileName, picBytes);
				} catch (Exception e) {
					System.out.println("Problem with picture load "+e.getMessage());
				}
			}
		}
	}
	
}
